package com.bzqn.baseframe;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;

import android.content.Context;

public class Utils {
	public static String convertStreamToString(InputStream is) {

		BufferedReader reader = new BufferedReader(new InputStreamReader(is));

		StringBuilder sb = new StringBuilder();

		String line = null;

		try {

			while ((line = reader.readLine()) != null) {

				sb.append(line + "/n");

			}

		} catch (IOException e) {

			e.printStackTrace();

		} finally {

			try {

				is.close();

			} catch (IOException e) {

				e.printStackTrace();

			}

		}

		return sb.toString();

	}

	/**
	 * DIP TO PX
	 * 
	 * @param dipValue
	 * @return
	 */
	public static int dip2px(float dipValue, Context context) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dipValue * scale + 0.5f);
	}

	/**
	 * PX TO DIP
	 * 
	 * @param dipValue
	 * @return
	 */
	public static int px2dip(float pxValue, Context context) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	public static void copy(Reader in, Writer out) throws IOException {
		int c = -1;
		while ((c = in.read()) != -1) {
			out.write(c);
		}
	}

	public static String readFile(String fileName) throws IOException {
		Reader in = new FileReader(fileName);
		StringWriter out = new StringWriter();
		copy(in, out);
		return out.toString();
	}

	public static void saveFile(File file, String content) throws IOException {
		Writer writer = new FileWriter(file);
		writer.write(content);
		writer.close();
	}

	public static void saveFile(String content, File path) {
		FileOutputStream fos = null;
		try {
			if (!path.exists()) {// 文件不存在则创建
				path.createNewFile();
			} else {
				path.delete();
				path.createNewFile();
			}
			fos = new FileOutputStream(path);
			fos.write(content.getBytes());// 写入文件内容
			fos.flush();
		} catch (IOException e) {
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
				}
			}
		}
	}

}
